package logic

import (
	"context"
	"encoding/json"
	"manuscript-service/model/cache"
	"manuscript-service/model/mysql"
	"time"

	"manuscript-service/manrpc/internal/svc"
	"manuscript-service/manrpc/manrpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type ManListLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewManListLogic(ctx context.Context, svcCtx *svc.ServiceContext) *ManListLogic {
	return &ManListLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *ManListLogic) ManList(in *manrpc.ManListRequest) (*manrpc.ManListResponse, error) {
	// todo: add your logic here and delete this line

	var manuscr []mysql.Manuscript

	result, _ := cache.Rdb.Get(l.ctx, "manList").Result()
	if result == "" {
		mysql.DB.Find(&manuscr)

		jsonData, _ := json.Marshal(manuscr)
		cache.Rdb.Set(l.ctx, "manList", jsonData, time.Minute*120)
	} else {
		json.Unmarshal([]byte(result), &manuscr)
	}

	var manuscrList []*manrpc.ManList

	for _, manuscript := range manuscr {
		list := manrpc.ManList{
			Title:     manuscript.Title,
			Info:      manuscript.Info,
			ClassName: int64(manuscript.ClassId),
		}
		manuscrList = append(manuscrList, &list)
	}

	return &manrpc.ManListResponse{
		List: manuscrList,
	}, nil
}
